package com.mdp.tpa.pay.wxpay.service;


import com.google.gson.Gson;
import com.mdp.tpa.client.entity.AppTpAuth;
import com.mdp.tpa.client.entity.AppTpPay;
import com.mdp.tpa.client.service.AppTpAuthService;
import com.mdp.tpa.client.service.AppTpPayService;
import com.mdp.tpa.pay.cm.entity.Orders;
import com.mdp.tpa.pay.cm.service.OrdersService;
import com.mdp.tpa.pay.wxpay.config.WxpayConfig;
import com.mdp.tpa.pay.wxpay.enums.WxApiType;
import com.mdp.tpa.pay.wxpay.enums.WxTradeState;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.util.EntityUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.io.IOException;
import java.math.BigDecimal;
import java.util.HashMap;
import java.util.Map;

@Service
public class WxpayPubService {

    @Resource
    private WxpayConfig wxPayConfig;

    @Autowired
    AppTpPayService appTpPayService;
    @Autowired
    AppTpAuthService appTpAuthService;


    @Autowired
    private OrdersService ordersService;

    @Autowired
    RedisCacheLock redisCacheLock;


    private Logger log= LoggerFactory.getLogger(WxpayPubService.class);


    public AppTpPay getAppTpPayByAuthId(String authId){
        AppTpAuth auth=appTpAuthService.getAppTpAuth(authId);
        return appTpPayService.getAppTpPayByTpAppid(auth.getAppid());
    }

    /**
     * 根据订单号查询微信支付查单接口，核实订单状态
     * 如果订单已支付，则更新商户端订单状态，并记录支付日志
     * @param order
     */
    @Transactional(rollbackFor = Exception.class)
    public String checkOrderStatus(Orders order) throws Exception {
        //调用微信支付查单接口
        String result = this.queryOrderFromWx(order.getId());

        Gson gson = new Gson();
        Map<String, Object> resultMap = gson.fromJson(result, HashMap.class);

        //获取微信支付端的订单状态
        String tradeState = (String) resultMap.get("trade_state");

        //判断订单状态
        if(WxTradeState.SUCCESS.getType().equals(tradeState)){
            log.warn("核实订单已支付 ===> {}", order.getId());
            //如果确认订单已支付则更新本地订单状态
            Map<String,Object> amount = (Map) resultMap.get("amount");
            int total =((Double) amount.get("total")).intValue();//此处返回的是分
            BigDecimal actualAmount = new BigDecimal(total).divide(new BigDecimal(100));
//            this.ordersService.payConfirm(order.getOtype(), order.getId(), actualAmount, (String) resultMap.get("transaction_id"),"1");
        }

        return tradeState;
    }

    public String queryOrderFromWx(String orderId) throws Exception {

        log.info("查单接口调用 ===> {}", orderId);

        String url = String.format(WxApiType.ORDER_QUERY_BY_NO.getType(), orderId);
        url = wxPayConfig.getDomain().concat(url).concat("?mchid=").concat(wxPayConfig.getMchId());

        HttpGet httpGet = new HttpGet(url);
        httpGet.setHeader("Accept", "application/json");

        //完成签名并执行请求
        CloseableHttpResponse response = wxPayConfig.getWxPayClient().execute(httpGet);

        try {
            String bodyAsString = EntityUtils.toString(response.getEntity());//响应体
            int statusCode = response.getStatusLine().getStatusCode();//响应状态码
            if (statusCode == 200) { //处理成功
                log.info("成功, 返回结果 = " + bodyAsString);
            } else if (statusCode == 204) { //处理成功，无返回Body
                log.info("成功");
            } else {
                log.info("查单接口调用,响应码 = " + statusCode+ ",返回结果 = " + bodyAsString);
                throw new IOException("request failed");
            }

            return bodyAsString;

        } finally {
            response.close();
        }

    }


    public static int DTI100(BigDecimal number){
        if(number==null){
            return 0;
        }else{

            return number.multiply(new BigDecimal("100")).intValue();
        }
    }

}
